import 'package:common_utils/common_utils.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/common/constants.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_author.dart';
import 'package:osc/models/entity/osc_base_entity.dart';
import 'package:osc/models/entity/osc_favorite_reverse_result_entity.dart';
import 'package:osc/models/entity/osc_project_detail_entity.dart';
import 'package:osc/models/entity/osc_soft.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/comment/comment_list.dart';
import 'package:osc/ui/pages/common_page.dart';
import 'package:osc/ui/widgets/comment/project_comment_bar_widget.dart';
import 'package:osc/ui/widgets/comment/project_comment_input_widget.dart';
import 'package:osc/ui/widgets/image_loader.dart';
import 'package:osc/ui/widgets/real_rich_text.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/web_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';

///软件
class ProjectDetailPage extends StatefulWidget {
  final int id;
  final String ident;
  const ProjectDetailPage({Key key, this.id = -1, this.ident = ""}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new ProjectDetailPageState(id, ident);
  }
}

class ProjectDetailPageState extends State<ProjectDetailPage> {
  int id;
  String ident;
  ProjectDetailPageState(this.id, this.ident);

  HttpRepository httpRepository;
  int page = 0;
  int size = 0;
  bool isLoadedData = false;
  int catalog;
  int replyId = 0;


  double paddingChildVertical = Dimens.gap_view_normal;

  OscProjectDetail project;
  OscProjectExtra projectExtra;
  OscAuthor author;
  String softwareLicense = "";
  String softwareLanguage = "";
  String softwareSupportOS = "";
  String softwareCollectionDate = "";
  String softwareTitle = "";
  String company = "";
  String authorName = "";
  String title = "";
  String logoUrl = "";
  String body = "";
  String commentContent = "";
  int comment = 0;
  bool favorite = false;
  int authorId;
  List<OscSoft> list;
  List<String> tags;


  String url = "";
  double progress = 0;


  FocusNode focusNode = FocusNode();
  bool showKeyBord = false;

  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
    refresh();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    double bottomHeight = MediaQuery.of(context).viewInsets.bottom;
    if (bottomHeight > 50) {
      showKeyBord = true;
    } else {
      showKeyBord = false;
      FocusScope.of(context).requestFocus(FocusNode());
    }
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
        appBar: AppBar(
          title: SizedBox(
            width: Dimens.view_item_icon_height_normal,
            height: Dimens.view_item_icon_height_normal,
            child: ImageLoader(url: logoUrl, fit: BoxFit.contain,),
          ),
          centerTitle: true,
          elevation: Dimens.gap_divider_height_smallest,
//          actions: null,
        ),
        body: buildBody(),
    );
  }

  buildBody(){
    return Stack(
      children: <Widget>[
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            buildTitle(),
            buildExtra(),
            buildContent(),
            ProjectCommentBarWidget(
                id: id,
                commentCount: comment,
                favorite: favorite,
                comment: commentContent,
                callback: ({
                  bool showInputWidget,
                  bool jump2CommentList,
                  bool reverseFavorite}){
                  if(showInputWidget){
                    setState(() {
                      showKeyBord = true;
                      FocusScope.of(context).requestFocus(focusNode);
                    });
                  } else if(jump2CommentList){
                    jumpToPageForResult(CommonPage(title: "评论列表", body: CommentList(id: id, type: 1,)));
                  } else if(reverseFavorite){
                    favoriteReverse();
                  }
                },
            ),
          ],
        ),
        Positioned(
          bottom: 0,
            child: Offstage(
              offstage: !showKeyBord,
              child: ProjectCommentInputWidget(content: commentContent, focusNode: focusNode, commentInputContentCallback: ({bool submit, String content}){
                if(submit){
                  publishComment(content);
                  commentContent = "";
                  showKeyBord = false;
                  FocusScope.of(context).requestFocus(FocusNode());
                  setState(() {

                  });
                } else {
                  commentContent = content;
                }
              },),
            )
        ),
      ],
    );
  }

  buildTitle(){
    List<TextSpan> textSpans = List<TextSpan>();
    textSpans.add(TextSpan(
      text: title,
      style: MyTextStyle.DETAIL_TITLE,
    ));
    textSpans.add(TextSpan(
      text: softwareTitle,
      style: MyTextStyle.DETAIL_SUB_TITLE,
    ));
    if(tags != null){
      for(String tag in tags){
        textSpans.add(SmallWidgets.buildImageSpan(imageName: "ic_label_$tag", margin: EdgeInsets.only(right: Dimens.gap_view_smaller)));
      }
    }
    return Padding(
        padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
      child: RealRichText(
        textSpanList: textSpans,
      ),
    );
  }

  buildExtra(){
    if(!StringUtil.isEmpty(softwareCollectionDate)){
      softwareCollectionDate = DateUtil.getDateStrByTimeStr(softwareCollectionDate, format: DateFormat.YEAR_MONTH_DAY);
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_big),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              child: Column(
                  children: [
                    buildTableItem("授权协议：", softwareLicense),
                    buildTableItem("操作系统：", softwareSupportOS),
                    buildTableItem("收录时间：", softwareCollectionDate),
                  ]
              )
          ),
          Expanded(
              child: Column(
                  children: [
                    buildTableItem("开发厂商：", company),
                    buildTableItem("开发语言：", softwareLanguage),
                    buildTableItem("提交者：", authorName, color: Colors.green),
                  ]
              )
          ),
        ],
      ),
    );
  }

  buildTableItem(String key, String value, {Color color = Colors.black54, double fontSize = Dimens.font_sp12}){
    return Offstage(
      offstage: StringUtil.isEmpty(value),
      child: Container(
        margin: EdgeInsets.symmetric(vertical: Dimens.gap_view_smaller),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 2,
              child: buildText(key, Colors.black54, fontSize),
            ),
            Expanded(
              flex: 3,
              child: SmallWidgets.buildText(value, color, fontSize, softWrap: true, overflow: TextOverflow.ellipsis),
            ),
          ],
        ),
      ),
    );
  }

  buildContent(){
    return Expanded(
      child: Container(
        margin: EdgeInsets.all(10.0),
        alignment: Alignment.center,
        child: StringUtil.isEmpty(body)?CircularProgressIndicator():buildWebView(),
      ),
    );
  }

  buildWebView(){
    return WebWidget(body: body,);
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    page = 1;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    List<OscSoft> tempList;
    int tempSize = 0;
    Future<OscBaseEntity<OscProjectDetail>> future;
    if(id > -1){
      future = httpRepository.getSoftDetail(id: id);
    } else {
      future = httpRepository.getSoftDetail(ident: ident);
    }
    await future.then((resp) {
      if (resp != null && resp.success) {
        project = resp.result;
        if (project != null) {
          id = project.id;
          title = project.title;
          tags = project.tags;
          projectExtra = project.extra;
          softwareSupportOS = projectExtra.softwareSupportOS;
          softwareCollectionDate = projectExtra.softwareCollectionDate;
          softwareLanguage = projectExtra.softwareLanguage;
          softwareLicense = projectExtra.softwareLicense;
          softwareTitle = projectExtra.softwareTitle;

          comment = project.statistics?.comment??0;
          print("---- commnetCount = $comment");
          favorite = project.favorite;
          author = project.author;
          if(author != null) {
            authorId = author.id;
            authorName = author.name;
          }
          body = project.body;
          if(project.image != null && project.image.href != null && project.image.href.length > 0){
            logoUrl = project.image.href[0];
          }
        }
      }
    });
    tempSize = tempList?.length??0;
    if(page == 1){
      list = tempList;
    } else {
      list.addAll(tempList);
    }
    size = list?.length??0;
    if(tempSize == Constant.PAGE_SIZE){
      page++;
    }
    if(mounted){
      setState(() {

      });
    }
  }

  favoriteReverse () async{
    await httpRepository.favoriteReverse(id: id, type: 1).then((resp){
      OscFavoriteReverseResultEntity entity = resp.result;
      if(entity != null) {
        setState(() {
          favorite = entity.favorite;
        });
        showTips(favorite ? "收藏成功" : "取消收藏");
      }
    });
  }

  publishComment(String content) async{
    if(StringUtil.isEmpty(content)){
      showTips("请输入评论内容");
      FocusScope.of(context).requestFocus(focusNode);
      return;
    }
    await httpRepository.commentSoft(id: id, replyId: replyId, content: content).then((resp) {
      showTips(resp.success? "评论成功" : "评论失败");
    });
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

}
